/* 
 * Copyright (C) 2014 Bartosz Stankiewicz.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301  USA
 */
package pl.poznan.put.et.kstio.invoice_ocr;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.ejb.Stateless;

import org.apache.log4j.Logger;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation;

import pl.poznan.put.et.kstio.invoice_ocr.model.InvoiceOcrProfile;
import pl.poznan.put.et.kstio.invoice_ocr.model.InvoiceOcrProfilePK;

/**
 * 
 * @author BartaZ
 */
@Stateless
public class PdfProfileBean implements PdfProfile {

	private static final Logger logger = Logger.getLogger(PdfProfileBean.class);
	
	public PdfProfileBean() {
		logger.debug("PdfProfileBean: constructor");
	}
	
	@PostConstruct
	private void init() {
		logger.debug("PdfProfileBean: init()");
	}
	
	@EJB
	private InvoiceOcrRepository ior;

	@Override
	public void saveProfile(File file, Map<String, String> metadata) throws IOException {
		InputStream is = new FileInputStream(file);
		PDDocument pdfDocument = null;
		try {
			pdfDocument = PDDocument.load(is);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
			throw new IOException("Problem z ładowaniem pliku PDF");
		}
		if (pdfDocument != null) {
			logger.debug("czytam metadane");
			if(metadata == null)
				throw new IOException("Nie ustawiono metadata");
			String nipString = metadata.get("nip").toString();
			String profileName = metadata.get("profileName").toString();
			if (nipString == null || profileName == null)
				throw new IOException("Nie ustawiono pola nip lub profileName w metadata");
			Long nip = Long.valueOf(nipString);
			
			logger.debug("czytam adnotacje");
			try {
				PDPage page = (PDPage) pdfDocument.getDocumentCatalog().getAllPages().get(0);
				float pageWidth = page.getMediaBox().getUpperRightX();
				float pageHeight = page.getMediaBox().getUpperRightY();
				List<InvoiceOcrProfile> newProfile = new ArrayList<InvoiceOcrProfile>();
				for (PDAnnotation annotation : page.getAnnotations()) {
					if ("FreeText".equals(annotation.getSubtype())) {
						InvoiceOcrProfile field = new InvoiceOcrProfile();
						field.setProfilePk(new InvoiceOcrProfilePK(nip, profileName, null, annotation.getContents()));
						field.setX(annotation.getRectangle().getLowerLeftX() / pageWidth);
						field.setY(annotation.getRectangle().getLowerLeftY() / pageHeight);
						field.setWidth(annotation.getRectangle().getWidth() / pageWidth);
						field.setHeight(annotation.getRectangle().getHeight() / pageHeight);
						field.setExpression1(annotation.getDictionary().getString("Subj"));
						newProfile.add(field);
					}
				}
				ior.register(newProfile);
			} catch (IOException e) {
				logger.error("Nie udalo sie zaladowac dokumentu albo pobrac pol", e);
				throw new IOException("Nie udalo sie zaladowac dokumentu albo pobrac pol: " + e.getMessage());
			}

			finally {
				if (pdfDocument != null) {
					try {
						pdfDocument.close();
					} catch (IOException e) {
						logger.error("Nie udalo sie zamknac dokumentu pdf", e);
						throw new IOException("Nie udalo sie zamknac dokumentu pdf: " + e.getMessage());
					}
				}
			}
		}
	}
}
